package com.tan.api.config;

import com.tan.core.enums.ErrorEnum;
import com.tan.core.exception.SystemException;
import com.tan.core.response.ApiResponse;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Tan
 * @description
 * @date 2025/2/6
 */
@Slf4j
@RestControllerAdvice
public class ErrorHandler {

    @ExceptionHandler(SystemException.class)
    public ApiResponse<ErrorEnum> handleSystemException(SystemException ex) {
        log.error("操作错误::", ex);
        return ApiResponse.create(ex.getErrorEnum().getCode(), ex.getMsg(), null);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse<ErrorEnum> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        List<String> errors = new ArrayList<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.add(String.format("参数[%s]错误: %s", fieldName, errorMessage));
        });
        return ApiResponse.create(ErrorEnum.PARAM_ERROR.getCode(), errors.toString(), null);
    }

    @ExceptionHandler(BindException.class)
    public ApiResponse<ErrorEnum> handleBindException(BindException ex) {
        List<String> errors = new ArrayList<>();
        for (FieldError error : ex.getBindingResult().getFieldErrors()) {
            String fieldName = ((FieldError) error).getField();
            errors.add(String.format("参数[%s]错误: %s", fieldName, error.getDefaultMessage()));
        }
        return ApiResponse.create(ErrorEnum.PARAM_ERROR.getCode(), errors.toString(), null);
    }

    @ExceptionHandler(Exception.class)
    public ApiResponse<ErrorEnum> handleGeneralException(Exception ex) {
//        ex.printStackTrace();
        log.error("发生错误::{}", ex);
        return ApiResponse.error(ErrorEnum.SERVER_ERROR);
    }
}
